package util;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * File relative operations utilities.
 */
public class FileUtil {

	/**
	 * Create destination file. If the path doesn't exist, create it first.<br/>
	 * But if the driver doesn't exist, god bless you.
	 * 
	 * @param destination
	 *            Full <b>local</b> path. Such as: c:\xbrl\ecr.xbrl or /tmp/xbrl/ecr.gz.
	 * @throws IOException
	 */
	public static File createFile(String destination) throws IOException {
		if (StringUtils.isBlank(destination)) {
			return null;
		}

		File destFile = new File(destination);

		int lastSeparatorIndex = destFile.getCanonicalPath().lastIndexOf(File.separator);
		String path = destination.substring(0, lastSeparatorIndex);
		File pathFile = new File(path);
		if (!pathFile.exists()) {
			FileUtils.forceMkdir(pathFile);
		}

		return new File(destination);
	}

	/**
	 * Get file path from file canonical name.
	 * <ul>
	 * <li>C:/dir/a.txt -> c:/dir</li>
	 * <li>a.txt -> IOException</li>
	 * </ul>
	 */
	public static String getFilePath(String fileFullName) throws IOException {
		File destFile = new File(fileFullName);
		destFile.getPath();
		int lastSeparatorIndex = destFile.getCanonicalPath().lastIndexOf(File.separator);
		if (lastSeparatorIndex < 0) {
			throw new IOException("Unable to find path for file: " + fileFullName);
		}
		return fileFullName.substring(0, lastSeparatorIndex);
	}
	
	/**
	 * Delete all files in folder.
	 * @param includeFolder If true, delete all files and folders. If false, only delete files.
	 */
	public static void deleteAllFilesInFolder(File folder, boolean includeFolder) {
		if (folder.isDirectory()) {
			for (File file : folder.listFiles()) {
				if (file.isDirectory()) {
					deleteAllFilesInFolder(file, includeFolder);
				} else {
					file.delete();
				}
			}
		}
	}

}

